<template>
  <BaseDialog
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    :title="product ? '编辑产品' : '新增产品'"
    width="600px"
    @close="handleClose"
  >
    <BaseForm
      ref="formRef"
      v-model="formData"
      :rules="rules"
      :loading="submitting"
      @submit="handleSubmit"
      @reset="handleClose"
    >
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12">
          <el-form-item label="产品代号" prop="productCode">
            <el-input
              v-model="formData.productCode"
              placeholder="请输入产品代号"
              clearable
            />
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12">
          <el-form-item label="产品名称" prop="productName">
            <el-input
              v-model="formData.productName"
              placeholder="请输入产品名称"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="产品描述" prop="productDesc">
        <el-input
          v-model="formData.productDesc"
          type="textarea"
          :rows="4"
          placeholder="请输入产品描述"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>

      <el-row :gutter="20" v-if="product">
        <el-col :xs="24" :sm="12">
          <el-form-item label="创建时间">
            <el-input
              :model-value="formatDateTimeForDisplay(product.createTime || '')"
              disabled
            />
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12">
          <el-form-item label="更新时间">
            <el-input
              :model-value="formatDateTimeForDisplay(props.product?.updateTime || '')"
              disabled
            />
          </el-form-item>
        </el-col>
      </el-row>

      <template #actions>
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          @click="handleSubmit"
          :loading="submitting"
          :disabled="submitting"
        >
          {{ submitting ? '提交中...' : '确定' }}
        </el-button>
      </template>
    </BaseForm>
  </BaseDialog>
</template>

<script setup lang="ts">
import { ref, watch, reactive } from 'vue';
import BaseDialog from '@/components/common/dialogs/BaseDialog.vue';
import BaseForm from '@/components/common/forms/BaseForm.vue';
import type { Product, CreateProductRequest, UpdateProductRequest } from '@/types/business/product';
import productService from '@/services/productService';
import { formatDateTimeForDisplay, getCurrentDateTime } from '@/utils/date';

const props = defineProps<{
  visible: boolean;
  product: Product | null;
}>();

const emit = defineEmits<{
  'update:visible': [value: boolean];
  close: [];
  success: [];
}>();

const formRef = ref();
const submitting = ref(false);

// 表单数据
const formData = reactive<{
  productCode: string;
  productName: string;
  productDesc?: string;
}>({
  productCode: '',
  productName: '',
  productDesc: ''
});

// 表单验证规则
const rules = {
  productCode: [
    { required: true, message: '请输入产品代号', trigger: 'blur' },
    { min: 2, max: 50, message: '长度应在 2 到 50 个字符之间', trigger: 'blur' }
  ],
  productName: [
    { required: true, message: '请输入产品名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度应在 2 到 100 个字符之间', trigger: 'blur' }
  ],
  productDesc: [
    { max: 500, message: '长度不能超过 500 个字符', trigger: 'blur' }
  ]
};

// 监听product变化，更新表单数据
watch(
  () => props.product,
  (newProduct) => {
    if (newProduct) {
      Object.assign(formData, { ...newProduct });
    } else {
      // 重置表单
      Object.assign(formData, {
        productCode: '',
        productName: '',
        productDesc: '',
        createTime: '',
        updateTime: ''
      });
    }
  },
  { immediate: true }
);

// 处理关闭
const handleClose = () => {
  emit('close');
};

// 处理提交
const handleSubmit = async () => {
  try {
    submitting.value = true;

    if (props.product && props.product.id) {
      // 更新产品
      const updatedProduct = {
        ...formData,
        updateTime: getCurrentDateTime()
      };

      await productService.updateProduct(props.product.id, updatedProduct);
    } else {
      // 创建产品
      const newProduct = {
        ...formData,
        createTime: getCurrentDateTime(),
        updateTime: getCurrentDateTime()
      };

      await productService.createProduct(newProduct);
    }

    emit('success');
  } catch (error: any) {
    console.error('产品提交失败:', error);
    throw error; // 让BaseForm处理错误消息
  } finally {
    submitting.value = false;
  }
};
</script>